package com.guaoran.solr;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guaoran.utils.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.beans.DocumentObjectBinder;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/5/23 15:24
 */
@Slf4j
public class SolrUtils {
    private static SolrClient client;
    private static String url;
    static{
        url = "http://127.0.0.1:8983/solr/test6";
        client = new HttpSolrClient.Builder(url).build();
    }

    /**
     * 保存索引内容
     * @param solrEntity
     * @param <T>
     * @return
     */
    private static<T> boolean addBean(T solrEntity){
        try {
//            client = new HttpSolrClient.Builder(url).build();
            client.addBean(solrEntity);
            client.commit();
//            client.close();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据策略进行是否创建索引词和索引内容
     * @param solrEntity
     * @param isCreateManagedSchema
     * @param <T>
     * @return
     */
    public static <T> boolean addBean(T solrEntity,boolean isCreateManagedSchema) {
        try {
            //是否创建 managed_schema索引
            if(isCreateManagedSchema){
//                Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
                String requestJson = getRequestJson(solrEntity.getClass());
                boolean flag = insertManagedSchema(url,requestJson);
                if(flag){
                    return addBean(solrEntity);
                }
            }else{
                return addBean(solrEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 获取报文请求的json参数
     * @param clazz
     * @param <T>
     * @return
     */
    private static <T> String getRequestJson(Class<T> clazz){
        StringBuffer bf = new StringBuffer();
        Field[] fields = clazz.getDeclaredFields();
        for (int j = 0; j < fields.length; j++) {
            //获取字段中包含Field的注解
            org.apache.solr.client.solrj.beans.Field meta = fields[j].getAnnotation(org.apache.solr.client.solrj.beans.Field.class);
            if(meta!=null&& !"id".equals(fields[j].getName())){
                String typeNames = fields[j].getType().getName();
                String [] typeNameArr = typeNames.split("\\.");
                String typeNameVal = typeNameArr[typeNameArr.length-1];
                JSONObject fieldVal = new JSONObject();
                fieldVal.put("name",fields[j].getName().toString());
                fieldVal.put("type",typeNameVal.toLowerCase().toString());
                if(j==0){
                    bf.append("{");
                }
                bf.append("\"add-field\":"+fieldVal);
                if(j==fields.length-1){
                    bf.append("}");
                }else {
                    bf.append(",");
                }
            }
        }
        return bf.toString();
    }

    /**
     * 插入索引词：主要是为了类型
     * @param requestUrl
     * @param requestJson
     * @return
     */
    public static boolean insertManagedSchema(String requestUrl,String requestJson){
        try {
            String url = requestUrl+"/schema";
            String result = MyHttpClient.getPostResponseWithHttpClient(url,"utf-8",requestJson);
            System.out.println(result);
            JSONObject resultObj = JSONObject.parseObject(result);
            Object obj = resultObj.get("errors");
            if(obj!=null){
                log.error("error={}",obj);
                return false;
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.error("insertManagedSchema...Exception:"+e);
            return false;
        }
    }

    /**
     * 查询
     * @param keywords
     * @param start
     * @param rows
     * @return
     * @throws SolrServerException
     * @throws IOException
     */
    public static QueryResponse query(String keywords,int start,int rows) throws SolrServerException, IOException {
        if(start==0&&rows==0){
            return query(keywords);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery(keywords);
        query.setStart(start);
        query.setRows(rows);
        query.setHighlight(true);
        return client.query(query);
    }

    /**
     * 删除solr 数据
     *
     * @param id
     */
    public static boolean removeSolrData(String id) {
        try {
            client.deleteById(id);
            client.commit();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 查询
     *
     * @param keywords
     */
    public static QueryResponse query(String keywords) throws SolrServerException, IOException {
        SolrQuery query = new SolrQuery();
        query.setQuery(keywords);
        QueryResponse rsp = client.query(query);
        return rsp;
    }
    public static void main(String[] args) throws Exception {
//        for (int i = 0;i<20;i++){//String name, String content,String id
//            SolrUtils.addBean(new ArticleVO("张三"+i,"我是测试"+i, UUID.randomUUID().toString()),false);
//        }
        QueryResponse response = query("测试",0,8);
        List<ArticleVO> vo = response.getBeans(ArticleVO.class);
        System.out.println(vo);

    }


}
